import axios from "axios";
import { UniAdapter } from "uniapp-axios-adapter";

const instance = axios.create({
  adapter: UniAdapter,
  timeout: 5000,
  baseURL: "http://localhost:3000/",
});

instance.interceptors.request.use(
  (config) => {
    const token = uni.getStorageSync("token");
    if (token) {
      config.headers.Authorization = `${token}`;
    }
    uni.showLoading({
      title: "加载中",
    });
    return config;
  },
  (error) => {
    uni.hideLoading();
    return Promise.reject(error);
  }
);

instance.interceptors.response.use((response) => {
  uni.hideLoading();
  const { data, statusCode, status } = response;
  console.log(status, statusCode);
  if (status != 201 && status != 200) {
    uni.showToast({
      title: data.message || "请求失败",
      icon: "none",
    });
    return Promise.reject(data);
  }

  uni.showToast({
    title: "请求成功",
    icon: "success",
    mask: true,
  });

  return response.data;
});

export default instance;
